package com.lemon.smartsafety.ui.activity.fire.item.statistics;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.baidu.location.BDLocation;
import com.lemon.android.http.Field;
import com.lemon.android.http.HttpUtils;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.entity.RefreshViewEntity;
import com.lemon.smartsafety.entity.baidu.BaiduMapResultEvent;
import com.lemon.smartsafety.entity.common.AreaVo;
import com.lemon.smartsafety.entity.common.EvidenceActionSheetType;
import com.lemon.smartsafety.entity.common.SelectDataI;
import com.lemon.smartsafety.entity.common.UploadFileItem;
import com.lemon.smartsafety.entity.event.common.AreaSelectEvent;
import com.lemon.smartsafety.entity.event.common.SelectItemEvent;
import com.lemon.smartsafety.entity.event.datacoll.ThreePersonEvent;
import com.lemon.smartsafety.entity.main.OptionItemVo;
import com.lemon.smartsafety.entity.safe.company.CompanyInfo;
import com.lemon.smartsafety.http.HttpBack;
import com.lemon.smartsafety.http.HttpOkBase;
import com.lemon.smartsafety.http.HttpPath;
import com.lemon.smartsafety.listener.AreaType;
import com.lemon.smartsafety.result.BaseMode;
import com.lemon.smartsafety.result.OldBaseMode;
import com.lemon.smartsafety.result.fire.FireCompanyBaseScore;
import com.lemon.smartsafety.result.fire.SuperviseCompanyDetail;
import com.lemon.smartsafety.result.fire.SuperviseCompanyResult;
import com.lemon.smartsafety.ui.activity.baidu.LemonBaiduActivity;
import com.lemon.smartsafetynew.ui.activity.base.PhotoSelectBaseActivity;
import com.lemon.smartsafety.ui.activity.common.AreaProvinceActivity;
import com.lemon.smartsafety.ui.activity.common.UnitPropActivity;
import com.lemon.smartsafety.ui.activity.fire.FirefightingUtil;
import com.lemon.smartsafety.ui.activity.safe.data.CompanyBasicThreePersonActivity;
import com.lemon.smartsafety.ui.adapter.common.SelectEvidenceAdapter;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.JsonUtils;
import com.lemon.smartsafety.utils.LogUtils;
import com.lemon.smartsafety.utils.app.ToastUtils;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.app.UserTypeHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.utils.location.LocationBaiDuUtils;
import com.lemon.smartsafety.utils.photo.GlideImageLoader;
import com.lemon.smartsafety.view.ViewFireTop;
import com.lemon.smartsafety.view.dialog.DialogSingleChose;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.Subscribe;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.Bind;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.model.PhotoInfo;

public class CompanyStatisticsActivity extends PhotoSelectBaseActivity {


    @Bind(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @Bind(R.id.fireTop)
    ViewFireTop fireTop;
    @Bind(R.id.metUnitName)
    MaterialEditText metUnitName;
    @Bind(R.id.metCode)
    MaterialEditText metCode;
    @Bind(R.id.metAddress)
    MaterialEditText metAddress;
    @Bind(R.id.txt_location)
    TextView txtLocation;
    @Bind(R.id.metUnitProp)
    MaterialEditText metUnitProp;
    @Bind(R.id.arrowUnitProp)
    ImageView arrowUnitProp;
    @Bind(R.id.rowUnitProp)
    TableRow rowUnitProp;
    @Bind(R.id.metArea)
    MaterialEditText metArea;
    @Bind(R.id.arrowArea)
    ImageView arrowArea;
    @Bind(R.id.rowArea)
    TableRow rowArea;
    @Bind(R.id.metThreePersonInfo)
    MaterialEditText metThreePersonInfo;
    @Bind(R.id.arrowThreePersonInfo)
    ImageView arrowThreePersonInfo;
    @Bind(R.id.rowThreePersonInfo)
    TableRow rowThreePersonInfo;
    @Bind(R.id.iv_photo)
    ImageView ivPhoto;
    @Bind(R.id.rowPhotoPick)
    TableRow rowPhotoPick;
    @Bind(R.id.mSelectRecycleView)
    RecyclerView mSelectRecycleView;
    @Bind(R.id.btn_submit)
    Button btnSubmit;
    @Bind(R.id.tr_button)
    TableRow trButton;
    @Bind(R.id.tl_basic_info)
    TableLayout tlBasicInfo;
    @Bind(R.id.mainContainer)
    LinearLayout mainContainer;
    @Bind(R.id.metRegisterAddress)
    MaterialEditText metRegisterAddress;
    private String mApplicationCode;
    private CompanyInfo mCompanyInfo;

    private boolean isSaferOrMajor = false;

    private PhotoInfo mPhotoInfo;


    private SelectDataI mUnitProp = null;
    private SelectDataI mAreaProvince, mAreaCity, mAreaDistrict, mAreaStreet, mAreaVillage;

    private Map<String, String> mThreePersonValue = new HashMap<>();
    private LocationBaiDuUtils locationBaiDuUtils;

    private String[] mCapital = {"江苏", "浙江", "上海"};
    private String[] mCity = {"无锡", "苏州", "南通", "常州"};
    private String[] mDistrict = {"江阴", "宜兴", "梁溪区", "滨湖区", "新吴区", "锡山区", "惠山区"};

    private DialogSingleChose dialogSingleChose;

    private SuperviseCompanyResult.ResultEntity resultEntity;
    private FireCompanyBaseScore fireCompanyBaseScore;

    private SuperviseCompanyDetail.MyCompanyScoreListEntity myCompanyScoreListEntity;

    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();
        if (getIntent().getExtras() != null) {
            resultEntity = (SuperviseCompanyResult.ResultEntity) getIntent().getSerializableExtra(BundleKey.FIRE_COMPANY_BASE_INFO);
            myCompanyScoreListEntity = (SuperviseCompanyDetail.MyCompanyScoreListEntity) getIntent().getSerializableExtra(BundleKey.FIRE_COMPANY_PRO_CODE);
        }
    }


    @Override
    protected void initTitle() {
        setBarTitle("单位信息完善率");
    }

    @Override
    protected void callFinish() {
        IApplication._tempBuildPropActivity = null;
        mCompanyInfo = null;
        mPhotoInfo = null;
        this.finish();
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_company_statistics;
    }


    @Override
    protected void initViews() {
        super.initViews();

        dialogSingleChose = new DialogSingleChose(this);

        fireTop.setTitleContent(resultEntity.getCompanyName());
        fireTop.setTitleSubContent("");
        fireTop.setNum1Content("0");
        fireTop.setNum2Content("/0");
        fireTop.setNum1Color(R.color.colorAppRed);
        fireTop.setNum2Color(R.color.colorAppBlue);
        fireTop.setImageCircleShow(true);
        fireTop.setImageCircleBg(R.drawable.shape_circle_red);


        metUnitProp.setTag("");
        ivPhoto.setTag("");
        metArea.setText("");
        metAddress.setMetHintTextColor(ContextCompat.getColor(this, R.color.text_30));
        metAddress.setMetTextColor(ContextCompat.getColor(this, R.color.colorTextPrimary));

        isSaferOrMajor = UserTypeHelper.isSaferOrMajor();

        IApplication._tempBuildPropActivity = this;
        initTopHttp();
        initCompanyBase();
    }


    /**
     * 刷新View
     *
     * @param companyInfo
     */
    private void initValueView(CompanyInfo companyInfo) {
        btnSubmit.setText("审核确认");

        metUnitName.setText(StringUtils.nullValue(companyInfo.getCompany_name()));
        if (isSaferOrMajor) {
            disableEditText(metUnitName);
        }

        metRegisterAddress.setText(companyInfo.getRegister_address());

        metArea.setText(getAreaText(companyInfo));
        metCode.setText(StringUtils.nullValue(companyInfo.getCompany_code()));
        if (isSaferOrMajor) {
            disableEditText(metCode);
        }

        String address = StringUtils.nullValue(companyInfo.getAddress());
        if (address.length() != 0) {
            metAddress.setText(StringUtils.nullValue(companyInfo.getAddress()));
        } else {
            getLoacation();
        }


        String unitPropId = StringUtils.nullValue(companyInfo.getType_id());
        String unitPropTitle = StringUtils.nullValue(companyInfo.getType_title());
        if (unitPropId.length() != 0 && unitPropTitle.length() != 0) {
            OptionItemVo vo = new OptionItemVo();
            vo.setSelected(true);
            vo.setVoId(unitPropId);
            vo.setTitle(unitPropTitle);
            mUnitProp = vo;
            metUnitProp.setText(unitPropTitle);
            metUnitProp.setTag(unitPropId);
        } else {
            metUnitProp.setTag("");
        }


        List<UploadFileItem> oldPhotos = companyInfo.getFiles();
        if (null != oldPhotos && oldPhotos.size() != 0) {
            addUploadFileItems(oldPhotos);
        }
        /* 营业执照 */
        String licensePhoto = companyInfo.getLicense_photo();
        if (StringUtils.nullValue(licensePhoto).length() != 0) {
            String url = HttpUtils.formatFilesUrl(licensePhoto);
            this.mPhotoInfo = new PhotoInfo();
            mPhotoInfo.setPhotoId(Integer.MAX_VALUE);
            mPhotoInfo.setPhotoPath(url);
            ivPhoto.setTag(url);
            GlideImageLoader.loadImage(this, url, ivPhoto);
        }


        mThreePersonValue = getThreePersonInfoValue(companyInfo);
        setThreePersonStatusText();


        if (CommonUtil.objIsEmpty(mUnitProp)) {
            finish();
        }

    }

    private boolean isMapEmpty(Map map) {
        if (map == null || map.isEmpty()) {
            return true;
        }
        return false;
    }

    @Subscribe
    public void onEventMainThread(ThreePersonEvent event) {
        if (event.getTag().equals(ThreePersonEvent.class.getName())) {
            if (event.getData() != null) {
                mThreePersonValue = event.getData();
                setThreePersonStatusText();
            }
        }
    }

    private void setThreePersonStatusText() {
        CharSequence allChar = StringUtils.getStatusString("已填完整", StringUtils.ColorStatus.STATUS_GREEN);
        CharSequence partChar = StringUtils.getStatusString("已填部分", StringUtils.ColorStatus.STATUS_YELLOW);
        CharSequence noneChar = StringUtils.getStatusString("未填", StringUtils.ColorStatus.STATUS_RED);
        if (!isMapEmpty(mThreePersonValue)) {
            metThreePersonInfo.setMetTextColor(getResources().getColor(R.color.colorTextSecondary));
            if (mThreePersonValue.size() == 9) {
                Set<String> keys = mThreePersonValue.keySet();
                boolean isAll = true;
                for (String key : keys) {
                    if (StringUtils.nullValue(mThreePersonValue.get(key)).length() == 0) {
                        isAll = false;
                        break;
                    }
                }
                metThreePersonInfo.setText(isAll ? allChar : partChar);
            } else {
                metThreePersonInfo.setText(partChar);
            }
        } else {
            metThreePersonInfo.setText(noneChar);
        }
    }


    @OnClick({R.id.btn_submit, R.id.txt_location})
    public void submitAction(View view) {

        switch (view.getId()) {
            case R.id.btn_submit:
                if (!validateForm()) {
                    return;
                }
                getConfirmDialog("是否提交？", new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (which == DialogAction.POSITIVE) {
                            doSubmitAction();
                        }
                    }
                }).show();
                break;
            case R.id.txt_location:
                startActivity(new Intent(this, LemonBaiduActivity.class));
                //getLoacation();
                break;
        }
    }

    @Subscribe
    public void onEventMainThread(BaiduMapResultEvent event) {

        if (event.getSearchMode() != null) {

            LogUtils.LOGE("定位页面返回地理位置成功");

            mAddress = event.getSearchMode().getAddress();
            //替换掉国家
            if (!CommonUtil.strIsEmpty(mAddress)) {
                mAddress = mAddress.replace(event.getSearchMode().getCountry(), "");
            }
            mLngLat = event.getSearchMode().getLatLng().longitude + "," + event.getSearchMode().getLatLng().latitude;
            mLng = String.valueOf(event.getSearchMode().getLatLng().longitude);
            mLat = String.valueOf(event.getSearchMode().getLatLng().latitude);

            metAddress.setText(mAddress);

        }


    }


    /**
     * 老的定位
     */
    private void getLoacation() {

        locationBaiDuUtils = new LocationBaiDuUtils(this);
        locationBaiDuUtils.setCallBackListen(new LocationBaiDuUtils.CallBackInterface() {
            @Override
            public void callBackFunction(boolean Success, BDLocation location) {
                LogUtils.LOGE("初始化本地时时地理位置成功");

                mAddress = location.getAddrStr();
                if (!CommonUtil.strIsEmpty(mAddress)) {
                    mAddress = mAddress.replace(location.getCountry(), "");
                }
                mLngLat = location.getLongitude() + "," + location.getLatitude();
                mLng = String.valueOf(location.getLongitude());
                mLat = String.valueOf(location.getLatitude());

                metAddress.setText(mAddress);
            }
        });
        locationBaiDuUtils.initLocation();
    }


    /**
     * 提交  单位信息
     */
    private void doSubmitAction() {
        final LemonRequestParams params = new LemonRequestParams("company_info", "company_id");

        params.put("handler", "com.lemon.company.CompanyFireInfoAction");
        params.put("op", "edit_company_info");

        params.put(LemonRequestParams._txtIdValues, mCompanyInfo.getCompany_id());
        params.put("company_id", mCompanyInfo.getCompany_id());
        params.put("txtCompanyName", StringUtils.nullValue(metUnitName.getText().toString().trim()), Field.TYPE_STRING);
        params.put("txtCompanyCode", StringUtils.nullValue(metCode.getText().toString().trim()), Field.TYPE_STRING);
        params.put("txtTypeId", StringUtils.nullValue(mUnitProp.getValue()), Field.TYPE_INT);
        params.put("txtAddress", StringUtils.nullValue(metAddress.getText().toString().trim()), Field.TYPE_STRING);
        params.put("txtRegisterAddress", StringUtils.nullValue(metRegisterAddress.getText().toString().trim()), Field.TYPE_STRING);
        params.putAll(mThreePersonValue, Field.TYPE_STRING);
        if (mAreaProvince != null) {
            params.put("selPositionProvinceId", mAreaProvince.getValue(), Field.TYPE_STRING);
        }
        if (mAreaCity != null) {
            params.put("selPositionCityId", mAreaCity.getValue(), Field.TYPE_STRING);
        }
        if (mAreaDistrict != null) {
            params.put("selPositionDistrictId", mAreaDistrict.getValue(), Field.TYPE_STRING);
        }
        if (mAreaStreet != null) {
            params.put("selPositionStreetsId", mAreaStreet.getValue(), Field.TYPE_STRING);
        }
        if (mAreaVillage != null) {
            params.put("selPositionVillageId", mAreaVillage.getValue(), Field.TYPE_STRING);
        }
        if (StringUtils.nullValue(mLngLat).length() != 0) {
            params.put("txtLocation", mLngLat, Field.TYPE_STRING);
        }
        if (StringUtils.nullValue(mLng).length() != 0) {
            params.put("txtLongitude", mLng, Field.TYPE_STRING);
        }
        if (StringUtils.nullValue(mLat).length() != 0) {
            params.put("txtDimensionality", mLat, Field.TYPE_STRING);
        }
        params.put("_no_html", "1");
        params.put("_txtDataSourceProvider", "com.lemon.fire_control.SafeConnProvider");


        getSinglePhotoUploadItem(mPhotoInfo, new SelectEvidenceAdapter.CropCallBack<String>() {
            @Override
            public void onStart() {
                mHUDUtil.showHUD();
            }

            @Override
            public void onFinish(String data) {
                if (StringUtils.nullValue(data).length() != 0) {
                    params.put("license_photo", data);
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        getUploadItems(new SelectEvidenceAdapter.CropCallBack<List<UploadFileItem>>() {
                            @Override
                            public void onStart() {
                                mHUDUtil.show();
                            }

                            @Override
                            public void onFinish(List<UploadFileItem> data) {
                                if (data != null && data.size() != 0) {
                                    params.put("files", mGson.toJson(data));
                                }
                                new Handler().post(new Runnable() {
                                    @Override
                                    public void run() {

                                        initCompanySave(params);
                                        //SafeDataServices.init().saveComInfoAction(params, true);
                                    }
                                });
                            }
                        });
                    }
                });

            }
        });
    }


    private boolean validateForm() {
        if (UserTypeHelper.isDataCollection()) {
            if (StringUtils.nullValue(metUnitName.getText().toString().trim()).length() == 0) {
                metUnitName.setError("请填写单位全称");
                mHUDUtil.showErrorTip(metUnitName.getError().toString());
                return false;
            }

            if (StringUtils.nullValue(metCode.getText().toString().trim()).length() == 0) {
                metCode.setError("请填写机构代码");
                mHUDUtil.showErrorTip(metCode.getError().toString());
                return false;
            }

            if (StringUtils.nullValue(metRegisterAddress.getText().toString().trim()).length() == 0) {
                metRegisterAddress.setError("请填注册地址");
                mHUDUtil.showErrorTip(metRegisterAddress.getError().toString());
                return false;
            }

            if (StringUtils.nullValue(metUnitProp.getText().toString().trim())
                    .length() == 0 || StringUtils.nullValue(metUnitProp.getTag().toString().trim()).length() == 0) {
                mHUDUtil.showErrorTip("请选择单位性质");
                return false;
            }


        }


//        if (StringUtils.nullValue(metUnitProp.getText().toString().trim()).length() == 0) {
//            mHUDUtil.showErrorTip("请选择单位性质");
//            return false;
//        }

        if (mAreaCity == null) {
            mHUDUtil.showErrorTip("请选择所属城市");
            return false;
        }

        return true;
    }

    @OnClick({R.id.rowUnitProp, R.id.metUnitProp})
    public void onUnitPropClick(View view) {
        Bundle bundle = new Bundle();
        if (mUnitProp != null && StringUtils.nullValue(mUnitProp.getValue()).length() != 0) {
            bundle.putString(BundleKey.OLD_SELECT_VALUE, mUnitProp.getValue());
        }
        UIHelper.showActivity(this, bundle, UnitPropActivity.class);
    }

    @OnClick({R.id.rowThreePersonInfo, R.id.metThreePersonInfo})
    public void onThreePersonInfoClick(View view) {
        Bundle bundle = new Bundle();
        if (!isMapEmpty(mThreePersonValue)) {
            bundle.putSerializable(BundleKey.THREE_PERSON_VALUE, (Serializable) mThreePersonValue);
        }
        UIHelper.showActivity(this, bundle, CompanyBasicThreePersonActivity.class);
    }


    @Subscribe
    public void onEventMainThread(SelectItemEvent event) {
        if (event.getTag().equals(EventTag.TAG_UNIT_PROP_SELECT)) {
            mUnitProp = event.getData();
            metUnitProp.setText(StringUtils.nullValue(mUnitProp.getTitle()));
            metUnitProp.setTag(StringUtils.nullValue(mUnitProp.getValue()));
        }
    }

    @OnClick({R.id.rowArea})
    public void onAreaClick(View view) {
        Bundle bundle = new Bundle();
        bundle.putBoolean(BundleKey.IS_FOR_REGISTER, false);
        UIHelper.showActivity(CompanyStatisticsActivity.this, bundle, AreaProvinceActivity.class);
    }

    @Override
    public void evidencePlusEventHandler(String tag) {
        if (this.getClass().getName().equals(tag)) {
            showActionSheet(EvidenceActionSheetType.CAMERA_ALBUM_MULTI);
        }
    }

    @OnClick({R.id.iv_photo, R.id.rowPhotoPick})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_photo:
                if ("0".equals(ivPhoto.getTag()) || "".equals(ivPhoto.getTag())) {
                    showSelectPhoto();
                } else {
                    PhotoInfo photoInfo = new PhotoInfo();
                    photoInfo.setPhotoId(Integer.MAX_VALUE);
                    photoInfo.setPhotoPath(StringUtils.nullValue(ivPhoto.getTag().toString()));
                    UIHelper.showPhotoView(CompanyStatisticsActivity.this, photoInfo);
                }
                break;
            case R.id.rowPhotoPick:
                showSelectPhoto();
                break;
        }
    }


    private String getAreaText(CompanyInfo infoVo) {
        StringBuilder sb = new StringBuilder();
        String title = StringUtils.nullValue(infoVo.getPlace_name_province());
        if (title.length() != 0) {
            sb.append(title);
            AreaVo vo = new AreaVo();
            vo.setSelectedI(true);
            vo.setTitle(title);
            vo.setVoId(StringUtils.nullValue(infoVo.getPosition_province_id()));
            mAreaProvince = vo;
        }

        String title2 = StringUtils.nullValue(infoVo.getPlace_name_city());
        if (title2.length() != 0) {
            sb.append("-" + title2);
            AreaVo vo = new AreaVo();
            vo.setSelectedI(true);
            vo.setTitle(title2);
            vo.setVoId(StringUtils.nullValue(infoVo.getPosition_city_id()));
            mAreaCity = vo;
        } else {
            mAreaCity = null;
            mAreaDistrict = null;
            mAreaStreet = null;
            mAreaVillage = null;
            return sb.toString();
        }

        String title3 = StringUtils.nullValue(infoVo.getPlace_name_district());
        if (title3.length() != 0) {
            sb.append("-" + title3);
            AreaVo vo = new AreaVo();
            vo.setSelectedI(true);
            vo.setTitle(title3);
            vo.setVoId(StringUtils.nullValue(infoVo.getPosition_district_id()));
            mAreaDistrict = vo;
        } else {
            mAreaDistrict = null;
            mAreaStreet = null;
            mAreaVillage = null;
            return sb.toString();
        }
        String title4 = StringUtils.nullValue(infoVo.getPlace_name_streets());
        if (title4.length() != 0) {
            sb.append("-" + title4);
            AreaVo vo = new AreaVo();
            vo.setSelectedI(true);
            vo.setTitle(title4);
            vo.setVoId(StringUtils.nullValue(infoVo.getPosition_streets_id()));
            mAreaStreet = vo;
        } else {
            mAreaStreet = null;
            mAreaVillage = null;
            return sb.toString();
        }

        String title5 = StringUtils.nullValue(infoVo.getPlace_name_village());
        if (title5.length() != 0) {
            sb.append("-" + title5);
            AreaVo vo = new AreaVo();
            vo.setSelectedI(true);
            vo.setTitle(title5);
            vo.setVoId(StringUtils.nullValue(infoVo.getPosition_village_id()));
            mAreaVillage = vo;
        } else {
            mAreaVillage = null;
        }
        return sb.toString();
    }

    @Subscribe
    public void onEventMainThread(AreaSelectEvent event) {
        if (AreaType.PROVINCE == event.getType()) {
            mAreaProvince = event.getData();
        } else if (AreaType.CITY == event.getType()) {
            mAreaCity = event.getData();
        } else if (AreaType.DISTRICT == event.getType()) {
            mAreaDistrict = event.getData();
        } else if (AreaType.STREET == event.getType()) {
            mAreaStreet = event.getData();
        } else if (AreaType.VILLAGE == event.getType()) {
            mAreaVillage = event.getData();
        }

        metArea.setText(getAreaViewValue());
    }

    private String getAreaViewValue() {
        StringBuilder sb = new StringBuilder();
        if (mAreaProvince != null) {
            String title = StringUtils.nullValue(mAreaProvince.getTitle());
            sb.append(title);
        } else {
            return sb.toString();
        }
        if (mAreaCity != null) {
            String title = StringUtils.nullValue(mAreaCity.getTitle());
            sb.append("-" + title);
        } else {
            mAreaCity = null;
            mAreaDistrict = null;
            mAreaStreet = null;
            mAreaVillage = null;
            return sb.toString();
        }

        if (mAreaDistrict != null) {
            String title = StringUtils.nullValue(mAreaDistrict.getTitle());
            sb.append("-" + title);
        } else {
            mAreaDistrict = null;
            mAreaStreet = null;
            mAreaVillage = null;
            return sb.toString();
        }


        if (mAreaStreet != null) {
            String title = StringUtils.nullValue(mAreaStreet.getTitle());
            sb.append("-" + title);
        } else {
            mAreaStreet = null;
            mAreaVillage = null;
            return sb.toString();
        }


        if (mAreaVillage != null) {
            String title = StringUtils.nullValue(mAreaVillage.getTitle());
            sb.append("-" + title);
        } else {
            mAreaVillage = null;
        }

        return sb.toString();
    }


    private Map<String, String> getThreePersonInfoValue(CompanyInfo infoVo) {
        Map<String, String> valueDic = new HashMap<>();
        if (StringUtils.nullValue(infoVo.getLegal_person()).length() != 0) {
            valueDic.put(CompanyBasicThreePersonActivity.kTxtLegalPerson, StringUtils.nullValue(infoVo.getLegal_person()));
        }
        if (StringUtils.nullValue(infoVo.getLegal_person_cid()).length() != 0) {
            valueDic.put(CompanyBasicThreePersonActivity.kTxtLegalPersonCid, StringUtils.nullValue(infoVo.getLegal_person_cid()));
        }
        if (StringUtils.nullValue(infoVo.getLegal_person_phone()).length() != 0) {
            valueDic.put(CompanyBasicThreePersonActivity.kTxtLegalPersonPhone, StringUtils.nullValue(infoVo.getLegal_person_phone()));
        }


        if (StringUtils.nullValue(infoVo.getFire_manager()).length() != 0) {
            valueDic.put(CompanyBasicThreePersonActivity.kTxtFireManager, StringUtils.nullValue(infoVo.getFire_manager()));
        }
        if (StringUtils.nullValue(infoVo.getFire_manager_cid()).length() != 0) {
            valueDic.put(CompanyBasicThreePersonActivity.kTxtFireManagerCid, StringUtils.nullValue(infoVo.getFire_manager_cid()));
        }
        if (StringUtils.nullValue(infoVo.getFire_manager_phone()).length() != 0) {
            valueDic.put(CompanyBasicThreePersonActivity.kTxtFireManagerPhone, StringUtils.nullValue(infoVo.getFire_manager_phone()));
        }


        if (StringUtils.nullValue(infoVo.getFire_responsible()).length() != 0) {
            valueDic.put(CompanyBasicThreePersonActivity.kTxtFireResponsible, StringUtils.nullValue(infoVo.getFire_responsible()));
        }
        if (StringUtils.nullValue(infoVo.getFire_responsible_cid()).length() != 0) {
            valueDic.put(CompanyBasicThreePersonActivity.kTxtFireResponsibleCid, StringUtils.nullValue(infoVo.getFire_responsible_cid()));
        }
        if (StringUtils.nullValue(infoVo.getFire_responsible_phone()).length() != 0) {
            valueDic.put(CompanyBasicThreePersonActivity.kTxtFireResponsiblePhone, StringUtils.nullValue(infoVo.getFire_responsible_phone()));
        }


        return valueDic;
    }

    /**
     * 显示选择照片的界面
     */
    public void showSelectPhoto() {
        showActionSheet(EvidenceActionSheetType.CAMERA_ALBUM_SINGLE);
        //showSelectSinglePhotoView();
    }


    @Override
    protected void onSinglePhotoSuccess(int requestCode, PhotoInfo photoInfo) {
        super.onSinglePhotoSuccess(requestCode, photoInfo);
        this.mPhotoInfo = photoInfo;
        ivPhoto.setTag(StringUtils.nullValue(photoInfo.getPhotoPath()));
        GlideImageLoader.loadImage(this, StringUtils.nullValue(photoInfo.getPhotoPath()), ivPhoto);
        setMultiSelect(true);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            callFinish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(EventTag.TAG_ONE_COMPANY);
        IApplication._tempBuildPropActivity = null;
    }


    public void initTopHttp() {
        LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");
        params.put("company_code", resultEntity.getCompanyCode());
        params.put("radio_code", myCompanyScoreListEntity.getTargetCode());

        mHUDUtil.show();
        HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.Get_score), "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                mHUDUtil.hidden();
                if (httpClient) {
                    BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                    if (!CommonUtil.objIsEmpty(baseMode)) {
                        if (HttpBack.httpBackError(baseMode)) {

                            try {
                                fireCompanyBaseScore = mGson.fromJson(mGson.toJson(baseMode.getResult()), FireCompanyBaseScore.class);
                                initTopScore();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        } else {
                            ToastUtils.toastMsg(baseMode.getMsg());
                        }
                    }
                }
            }
        });

    }

    /**
     * 初始化顶部信息
     */
    private void initTopScore() {
        fireTop.setNum1Color(FirefightingUtil.getScoreTextColor(fireCompanyBaseScore.getStatus()));
        fireTop.setNum2Color(R.color.colorAppBlue);
        fireTop.setNum1Content(fireCompanyBaseScore.getCompanyScore());
        fireTop.setNum2Content("/" + fireCompanyBaseScore.getAvgScore());
        fireTop.setImageCircleBg(FirefightingUtil.getScoreImgCircleColor(fireCompanyBaseScore.getStatus()));
    }


    public void initCompanyBase() {
        LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");
        params.put("company_code", resultEntity.getCompanyCode());

        mHUDUtil.show();
        HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.Get_one_company_by_id), "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                mHUDUtil.hidden();
                if (httpClient) {
                    BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                    if (!CommonUtil.objIsEmpty(baseMode)) {
                        if (HttpBack.httpBackError(baseMode)) {

                            try {
                                mCompanyInfo = mGson.fromJson(mGson.toJson(baseMode.getResult()), CompanyInfo.class);
                                if (!CommonUtil.objIsEmpty(mCompanyInfo)) {
                                    initValueView(mCompanyInfo);
                                } else {
                                    mHUDUtil.showErrorTip("出错了");
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        } else {
                            mHUDUtil.showErrorTip(baseMode.getMsg());
                        }
                    }
                }
            }
        });

    }


    /**
     * 保存
     */
    public void initCompanySave(LemonRequestParams params) {
     /*   SharedPreferencesServer mSharedPreferencesServer=new SharedPreferencesServer(IApplication.context());
        String serverUrl = mSharedPreferencesServer.getRequestUrl( UrlInfo.BIND_COMPANY_EDIT_ACTION );
        LogUtils.LOGE("serverUrl:"+serverUrl);*/

        mHUDUtil.show();
        HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.Add_fire_company), "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                mHUDUtil.hidden();
                if (httpClient) {
                    OldBaseMode oldBaseMode = JsonUtils.fromJson(result, OldBaseMode.class);
                    if (!CommonUtil.objIsEmpty(oldBaseMode)) {
                        if (!oldBaseMode.isIsError()) {
                            ToastUtils.toastMsg(oldBaseMode.getError().getMsg());
                            //mHUDUtil.showDoneTip(oldBaseMode.getError().getMsg());
                            AppService.getBus().post(new RefreshViewEntity(CompanyStatisticsActivity.class.getName()));
                            callFinish();
                        } else {
                            //oldBaseMode.getError().getMsg();
                            mHUDUtil.showErrorTip(oldBaseMode.getError().getMsg());
                        }
                    }
                }
            }
        });

    }


}
